package com.hxx.uitls;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.DruidPooledConnection;

import java.io.InputStream;
import java.sql.SQLException;
import java.util.Properties;

//连接池工具类
public class DbPoolConnection {
    //单例模式
    private static DbPoolConnection databasePool = null;
    private DbPoolConnection(){}
    //锁住方法
    public static synchronized DbPoolConnection getInstance(){
        if (databasePool==null) {
             databasePool = new DbPoolConnection();
        }
        return databasePool;
    }

    //连接池的数据源
    private static DruidDataSource dds = null;

    //静态块，读取属性文件-->获取数据源
    static {
        //创建一个属性对象
        Properties properties = new Properties();
        try(InputStream in = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("jdbcInfo.properties")) {
            //加载文件
            properties.load(in);
            //数据源
            dds = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //返回数据库的连接
    public DruidPooledConnection getConnection(){
        try {
            return dds.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}